int freeRam () {
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

void printIntHex(__FlashStringHelper *s, int v) { 
  Serial.print(s);
  Serial.print(": ");
  Serial.println(v, HEX);
}

void printRam() {
  extern int __heap_start, __bss_start, __data_start, *__brkval;
  int stack;
  int heapend;

  if((int)__brkval == 0) {
    heapend = (int)&__heap_start;
  } 
  else {
    heapend = (int) __brkval;
  }

  printIntHex(F("End of RAM:   "), RAMEND);
  printIntHex(F("Stack pointer:"), SP);
  printIntHex(F("Stack pointer:"), (int) &stack);
  printIntHex(F("Heap end:     "), heapend);
  printIntHex(F("Heap start:   "), (int) &__heap_start);
  printIntHex(F("BSS start     "),   (int) & __bss_start);
  printIntHex(F("Data start    "),   (int) & __data_start);
  Serial.print(F("Free RAM      "));
  Serial.println(freeRam());

}

int d2u(int d) {
  return MIN_PULSE_WIDTH + int(float(d) * servo_scale);
}

int u2d(int u) {
  return int(float(u - MIN_PULSE_WIDTH) / servo_scale + 0.5);
}

// like strtok: first call established position, subsequent calls use last position

char *_gip;

int get_int(char *c) {
  _gip = c;
  return get_int();
}

int get_int() {
  char *c = _gip;
  int i = 0;
  int sign = 1;
  if (*c == '-') {
    c++;
    sign = -1;
  }
  for (;;) {
    if ((*c >= '0') && (*c <= '9')) {
      i = i * 10 + (*c - '0');  
      c++;
    } else {
      break;
    }
  }
  
  c++; // eat delimiter
  _gip = c;
  return sign * i;
}

char *_gihp;

byte get_int_hex(char *c) {
  _gihp = c;
  return get_int_hex();
}
   
byte get_int_hex() {
  char *c = _gihp;
  uint32_t i = 0;
  for (;;) {
    if ((*c >= '0') && (*c <= '9')) {
      i = (i << 4) + (*c - '0');  
      c++;
    } 
    else {
      if ((*c >= 'a') && (*c <= 'f')) {
        i = (i << 4) + (*c - 'a' + 10);
        c++;
      } 
      else {
        if ((*c >= 'A') && (*c <= 'F')) {
          i = (i << 4) + (*c - 'A' + 10);
          c++;
        } else {
         break;
        } 
      }
    }
  }
  c++;  // eat delimiter
  _gihp = c;
  return i;
}


